<?php
class ExportXmlPageAdminForm extends Form
{
	function ExportXmlPageAdminForm(){
		Form::Form('ExportXmlPageAdminForm');
		CGlobal::$website_title="Export Pages To Xml";
	}
	
	function draw(){
		global $display;
        $total_row = DB::fetch('SELECT count(*) AS total_row FROM `page` LIMIT 0,1','total_row',0);
        $xml = "<?xml version='1.0' encoding='utf-8' ?>\n\t\t";
        $xml .= "<pages>\n\t";
        if($total_row){
            $pages = DB::fetch_all_array('SELECT * FROM  `page`');
            if($pages){

                foreach($pages as $page){
                    $xml .= "<". $page['name']. ">\n\t\t";
                    $xml .= "<title>". $page['title']. "</title>\n\t\t";
                    $xml .= "<description>". $page['description']. "</description>\n\t\t";
                    $xml .= "<layout>". $page['layout']. "</layout>\n\t";
                    $blocks=DB::fetch_all_array('SELECT block.id, block.module_id, module.`name` as module_name, block.page_id, block.region, block.position, block.container_id FROM block INNER JOIN module ON block.module_id = module.id WHERE block.page_id = '.$page['id']);
                    if($blocks){
                        $xml .= "\t";
                        $region = '';
                        $i = 0;
                        $count_region = 0;
                        $xml .= "<regions>\n\t\t\t";
                        foreach($blocks as $block){
                            $count_region++;
                            if($region != $block['region']){
                                $region = $block['region'];
                                $xml .= "<region name='". $region. "'>\n\t\t\t\t";
                            }
                            $xml .= "<module name='". $block['module_name']. "' position='". $block['position']. "' container='". $block['container_id']. "'/>\n\t\t\t";
//                            var_dump($region, $blocks[$i+1]['region']);
                            if(!isset($blocks[$i+1]) || $region != $blocks[$i+1]['region']){
                                $xml .= "</region>\n\t\t";
                                if($count_region < sizeof($blocks)) $xml .= "\t";
                            }else{
                                $xml .= "\t";
                            }
                            $i++;
                        }
                        $xml .= "</regions>\n\t";

                    }
                    $xml .= "</".$page['name'].">\n\t\t\n\t";
                }
            }
        }
        $xml .= "</pages>";
        $xmlobj = new SimpleXMLElement($xml);
        $xmlobj->asXML(ROOT_PATH . 'export/pages.xml');
        echo 'export done: <a href="' . ROOT_PATH . 'export/pages.xml">pages.xml</a>';
	}
}
?>